<?php declare(strict_types=1);

namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Server\Contract\MiddlewareInterface;
use App\Model\SystemMenu;

/**
 * 总后台鉴权-中间件
 * Class AdminAucMiddleware
 * @package App\Http\Middleware
 * @Bean()
 */
class AdminAucMiddleware implements MiddlewareInterface
{
        /**
         * Process an incoming server request.
         *
         * @param ServerRequestInterface $request
         * @param RequestHandlerInterface $handler
         *
         * @return ResponseInterface
         * @inheritdoc
         */
        public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
        {
                $arrAuthResult = $this->authentication();
                if (!$arrAuthResult['success']) return response()->withStatus(401)->withContent($arrAuthResult['msg']);
                $response = $handler->handle($request);
                return $response;
        }

        public function authentication()
        {
                $strUserId = request()->userId;
                if ($strUserId === 'lcl00000004-0819-e715-a6cf-dcf0210560ae') return ['success' => true];
                $strPath = route(2)->getPath();
                $strMethod = request()->getMethod();
                $arrWhere = ['path' => $strPath, ['whereIn', 'method', [$strMethod, 'all']], 'menuType' => 2, 'status' => 1];
                $arrField = ['menuId', 'urlParams', 'pathParams', 'powerDiscern'];
                $arrMenu = SystemMenu::getOne($arrWhere, $arrField);
                if (!$arrMenu) return ['success' => false, 'msg' => 'Unknown request address or method'];
                if ($arrMenu['pathParams']) {
                        $arrPathParams = json_decode($arrMenu['pathParams'], true);
                        $arrVerifyParams = route(2)->getParams();
                        foreach ($arrPathParams as $k => $v) {
                                if ($v === '*') continue;
                                if (!isset($arrVerifyParams[$k]) || $arrVerifyParams[$k] != $v) {
                                        return ['success' => false, 'msg' => 'You do not have the operation permission. If you have any questions, contact the administrator！：' . $arrMenu['powerDiscern']];
                                }
                        }
                }
                if ($arrMenu['urlParams']) {
                        $arrUrlParams = json_decode($arrMenu['urlParams'], true);
                        $arrVerifyParams = request()->getQueryParams();
                        foreach ($arrUrlParams as $k => $v) {
                                if ($v === '*') continue;
                                if (!isset($arrVerifyParams[$k]) || $arrVerifyParams[$k] != $v) {
                                        return ['success' => false, 'msg' => 'You do not have the operation permission. If you have any questions, contact the administrator！：' . $arrMenu['powerDiscern']];
                                }
                        }
                }
                $arrWhere = [
                        'system_user_role.userId' => $strUserId,
                        'system_role.status' => 1,
                        'system_menu.status' => 1,
                        'system_role_permissions.menuId' => $arrMenu['menuId']
                ];
                $arrJoin['system_role_permissions'] = [
                        'table' => 'system_role_permissions',
                        'where' => ['system_role_permissions.menuId', '=', 'system_menu.menuId']
                ];
                $arrJoin['system_role'] = [
                        'table' => 'system_role',
                        'where' => ['system_role.roleId', '=', 'system_role_permissions.roleId']
                ];
                $arrJoin['system_user_role'] = [
                        'table' => 'system_user_role',
                        'where' => ['system_user_role.roleId', '=', 'system_role.roleId']
                ];
                $strCheckAuc = SystemMenu::getFieldValue($arrWhere, 'system_menu.menuId', [], $arrJoin);
                if (!$strCheckAuc) return ['success' => false, 'msg' => 'You do not have the operation permission. If you have any questions, contact the administrator！：' . $arrMenu['powerDiscern']];
                return ['success' => true];
        }
}